from django.http import JsonResponse
from django.shortcuts import render,redirect,reverse
from django.views.decorators.csrf import csrf_exempt
import json
from django.views.decorators.http import require_POST
from .utils import utils
from chat.models import Notes

# 假设有一个简单的消息存储，实际项目中你可能需要数据库
MESSAGES = []

@csrf_exempt
def send_message(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        message = data.get('msg1')
        if message:
            MESSAGES.append(message)
            return JsonResponse({"status": "success", "message": "Message sent."})
        else:
            return JsonResponse({"status": "error", "message": "No message provided."}, status=400)

def get_messages(request):
    last_message_id = request.GET.get('last_message_id', 0)
    # 这里简化处理，实际应用中应根据last_message_id查询新消息
    new_messages = [msg for msg in MESSAGES[int(last_message_id):]]
    return JsonResponse({"messages": new_messages})

@require_POST
def pub_notes(request):
    apk_id = request.POST.get('apk_id')
    question = request.POST.get('question')
    # print("question:",question)
    try:
        answer = utils.sample_sync_call(question)
        # print("answer:",answer)
        Notes.objects.create(apk_id=apk_id, question=question, answer=answer)
        return redirect(reverse("apk_detail",kwargs={'apk_id':apk_id}))
    except Exception as e:
        answer = str(e)
        Notes.objects.create(apk_id=apk_id, question=question, answer=answer)
        return redirect(reverse("apk_detail",kwargs={'apk_id':apk_id}))

def ai_window(request):
    return render(request,'chat/ai_window.html')

@require_POST
def ai_help(request):
    try:
        data = json.loads(request.body.decode('utf-8'))
        user_input = data.get('msg1')
        msg2=utils.sample_sync_call(user_input)
        response = JsonResponse({'msg2': msg2}, status=200)
        print(response)
        response["Access-Control-Allow-Origin"] = "*"
        response["Access-Control-Allow-Methods"] = "POST"
        return response
        # return redirect(reverse("chat/ai_window",kwargs={'msg2':msg2}))
    except Exception as e:
        return render(request,'chat/ai_window.html')